package com.trex.modules.tbl.web;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.trex.modules.tbl.checkman.entity.TblZdJcr;
import com.trex.modules.tbl.checkman.service.TblZdJcrService;
import com.trex.modules.tbl.entity.ServerTrexConfig;
import com.trex.modules.tbl.lineform.entity.TblXdZxxdctzd;
import com.trex.modules.tbl.lineform.service.TblXdZxxdctzdService;
import com.trex.modules.tbl.replyform.entity.TblXdJxchsd;
import com.trex.modules.tbl.service.TblXdLjzyjlService;
import com.trex.modules.tbl.workerplace.dao.TblZdWorkerdzDao;
import com.trex.modules.utils.JsonGenerator;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.common.web.http.HttpClientUtils;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.trex.modules.tbl.dw.entity.TblDwPro;
import com.trex.modules.tbl.dw.service.TblDwProService;
import com.trex.modules.tbl.entity.TblXdLjzyjl;
import com.trex.modules.tbl.entity.impl.MainModel;
import com.trex.modules.tbl.entity.impl.SecondModel;
import com.trex.modules.tbl.entity.impl.SysinfoModel;
import com.trex.modules.tbl.service.TblXdDjzyjlService;
import com.trex.modules.utils.TimeUtils;

import static com.trex.modules.tbl.web.TblXdLjzyjlController.parseJsonToListOfMap;
import static com.trex.modules.utils.JsonGenerator.sendGetRequestAndExtractUserId;
import static com.trex.modules.utils.JsonGeneratorDetail.createJson;
import static com.trex.modules.utils.JsonSenderUtil.sendJsonWithHttpClient;
import static java.lang.Thread.sleep;

/**
 * 动检作业记录Controller
 * @author jy
 * @version 2022-08-29
 */
@Controller
@RequestMapping(value = "/tbl/tblXdDjzyjl")
public class TblXdDjzyjlController extends BaseController {

	@Autowired
	private TblXdDjzyjlService tblXdDjzyjlService;
	@Autowired
	private TblDwProService tblDwProService;
	@Resource
	private AmqpTemplate amqpTemplate;
	@Autowired
	private TblZdJcrService tblZdJcrService;
	@Autowired
	private TblXdLjzyjlService tblXdLjzyjlService;
	@Autowired
	private TblZdWorkerdzDao tblZdWorkerdzDao;
	@Autowired
	private TblXdZxxdctzdService tblXdZxxdctzdService;



	private final ServerTrexConfig serverTrexConfig;

    public TblXdDjzyjlController(ServerTrexConfig serverTrexConfig) {
        this.serverTrexConfig = serverTrexConfig;
    }


    /**
	 * 获取数据
	 */
	@ModelAttribute
	public TblXdLjzyjl get(String recId, boolean isNewRecord) {
		return tblXdDjzyjlService.get(recId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	//@RequiresPermissions("tbl:tblXdLjzyjl:view")
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(value = "userid", required = false) String userid,
					   @RequestParam(value = "postid", required = false) String postid,TblXdLjzyjl tblXdLjzyjl, Model model, HttpServletRequest request) {
		int hours = new Date().getHours();
		if(hours >= 8 &&  hours < 19) {
			tblXdLjzyjl.setShift("2");
		}else {
			tblXdLjzyjl.setShift("1");
		}
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();
		logger.info("Received userid:\"!!!!!!!!!!!!!!!!!!!!!!!!!\"+\"______\"+ " + userid);

		// 如果 `userid` 从 URL 中传递，可以手动设置到 `tblXdLjzyjl`
		tblXdLjzyjl.setUserid(userid);
		String I_IP_ADDR = request.getRemoteHost();

		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);
		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdDjzyjlList";
	}




	@RequestMapping(value = {"list1", ""})
	public String list1(@RequestParam(value = "userid", required = false) String userid,
					   @RequestParam(value = "postid", required = false) String postid,TblXdLjzyjl tblXdLjzyjl, Model model, HttpServletRequest request) {
		int hours = new Date().getHours();
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		if(hours >= 8 &&  hours < 19) {
			tblXdLjzyjl.setShift("2");
		}else {
			tblXdLjzyjl.setShift("1");
		}
		// 获取当前时间
		LocalDateTime now = LocalDateTime.now();
		logger.info("Received userid:\"!!!!!!!!!!!!!!!!!!!!!!!!!\"+\"______\"+ " + userid);

		// 如果 `userid` 从 URL 中传递，可以手动设置到 `tblXdLjzyjl`
		tblXdLjzyjl.setUserid(userId);
		String I_IP_ADDR = request.getRemoteHost();
		List<TblXdZxxdctzd> lineList = tblXdZxxdctzdService.selectLine1(userId); ;
		model.addAttribute("lineList", lineList);

		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdDjzyjlList1";
	}


	/**
	 * 查询列表数据
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:view")
	@RequestMapping(value = "listData1")
	@ResponseBody
	public Page<TblXdLjzyjl> listData1(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		tblXdLjzyjl.setPage(new Page<>(request, response));
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		StringBuilder strWhere = new StringBuilder();
		if (tblXdLjzyjl.getStartTime() != null && tblXdLjzyjl.getEndTime() != null) {
			String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tblXdLjzyjl.getStartTime());
			String endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tblXdLjzyjl.getEndTime());
			strWhere.append(" AND A.STATION_TIME >= '").append(startTime).append("' ")
					.append(" AND A.STATION_TIME <= '").append(endTime).append("' ");

			if (tblXdLjzyjl.getStationCode() != null) {
				strWhere.append(" AND LEFT(A.LINE_CODE, 2) = '").append(tblXdLjzyjl.getStationCode()).append("' ");
			}
			tblXdLjzyjl.getSqlMap().put("extWhere", strWhere.toString());
			tblXdLjzyjl.setUserid(userId);
			Page<TblXdLjzyjl> page = tblXdDjzyjlService.findPage(tblXdLjzyjl);
			return page;

	}
	return null;
	}
	
	/**
	 * 查询列表数据
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<TblXdLjzyjl> listData(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		//数据库中取userId
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);
		tblXdLjzyjl.setPage(new Page<>(request, response));
		String shift = tblXdLjzyjl.getShift(); //班制
		Date stationTime = tblXdLjzyjl.getStationTime(); //日期
		if(stationTime != null) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			formatter.format(stationTime);
			Calendar cal = new GregorianCalendar();
			cal.setTime(stationTime);
			if ("1".equals(shift)) {
				//夜班
				cal.setTime(stationTime);
				cal.add(Calendar.DATE, -1);
				Date stationTimeE = cal.getTime();
				String timeEnded = null;
				String timeGte = formatter.format(stationTime);
				String timeLte = formatter.format(stationTimeE);
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				timeEnded = timeLte.substring(0, 10) + " 19:00:00";
				timeGte = timeGte.substring(0, 10) + " 08:00:00";
				timeLte = timeEnded;

				tblXdLjzyjl.setStationTime_gte(format.parse(timeLte));
				tblXdLjzyjl.setStationTime_lte(format.parse(timeGte));

			} else {
				cal.setTime(stationTime);
				cal.add(Calendar.DATE, 0);
				Date stationTimeE = cal.getTime();
				String timeEnded = null;
				String timeGte = formatter.format(stationTime);
				String timeLte = formatter.format(stationTimeE);
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//白班
				timeGte = timeGte.substring(0, 10) + " 08:00:00";
				timeLte = timeGte.substring(0, 10) + " 19:00:00";
				tblXdLjzyjl.setStationTime_gte(format.parse(timeGte));
				tblXdLjzyjl.setStationTime_lte(format.parse(timeLte));
			}


			tblXdLjzyjl.setStationTime(null);
			tblXdLjzyjl.setShift(null);

			if (tblXdLjzyjl.getStationCode() != null) {
				String strWhere = " AND LEFT(A.LINE_CODE,2) = '" + tblXdLjzyjl.getStationCode() + "' ";
				tblXdLjzyjl.getSqlMap().put("extWhere", strWhere);
			}
			tblXdLjzyjl.setUserid(userId);
			tblXdLjzyjl.setRoleId(EmpUtils.getOffice().getOfficeCode());
			Page<TblXdLjzyjl> page = tblXdDjzyjlService.findPage(tblXdLjzyjl);
			return page;
		}
		return null;
	}

	/**
	 * 确认框
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:view")
	@RequestMapping(value = "form")
	public String form(TblXdLjzyjl tblXdLjzyjl, Model model) {
//		int hours = new Date().getHours();
//		if(hours >= 8 &&  hours < 19) {
//			tblXdLjzyjl.setShift("2");
//		}else {
//			tblXdLjzyjl.setShift("1");
//		}
//		tblXdLjzyjl.setStationTime(TimeUtils.getCurrentDate());
		List<TblZdJcr> jcrList = tblZdJcrService.findList(new TblZdJcr()); // 检车人
		model.addAttribute("jcrList", jcrList);
		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl);
		return "modules/tbl/tblXdDjzyjlForm";
	}
	
	/**
	 * 结束框
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:view")
	@RequestMapping(value = "form2")
	public String form2(TblXdLjzyjl tblXdLjzyjl, Model model) {
		TblXdLjzyjl tblXdLjzyjl_new = this.get(tblXdLjzyjl.getRecId(), false);
		tblXdLjzyjl_new.setPassword("");
		model.addAttribute("tblXdLjzyjl", tblXdLjzyjl_new);
		return "modules/tbl/tblXdDjzyjlForm2";
	}

	/**
	 * 保存数据
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated TblXdLjzyjl tblXdLjzyjl) {
		tblXdDjzyjlService.save(tblXdLjzyjl);
		return renderResult(Global.TRUE, text("保存动检作业记录成功！"));
	}
	
	/**
	 * 检车确认
	 * @throws SQLException 
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:edit")
	@RequestMapping(value = "updateJCR")
	@ResponseBody
	public HashMap<String, Object> updateJCR(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
		HashMap<String, Object> map = new HashMap<>();
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		logger.info("9999999999999999999999+_____" + userId);

		String userName = tblZdWorkerdzDao.selectName1(userId);
		//实体类中无数据所以查数据库
		String JcrName = tblXdLjzyjlService.selectJnrName(tblXdLjzyjl.getJcrCode());
		String I_IP_ADDR = request.getRemoteHost(); // 取IP
		String I_USERCODE = UserUtils.getUser().getUserCode(); // 取用户id
		String I_USERNAME = UserUtils.getUser().getUserName(); //用户名

		map.put("I_LJZYBH", tblXdLjzyjl.getRecId()); 	// 列检记录编号 传入的REC_ID
		map.put("I_PASSWORD", tblXdLjzyjl.getPassword());	// 口令
		map.put("I_JCRCODE", tblXdLjzyjl.getJcrCode()); // 检车人ID
		map.put("I_JCRNAME", JcrName); // 检车人名字
		map.put("I_USERCODE", userId); // 登录人用户编号
		map.put("I_USERNAME", userName); // 登录用户名称
		map.put("I_IP", I_IP_ADDR); // 本机IP地址
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1
		
		try {
			tblXdDjzyjlService.updateJCR(map);
		} catch (SQLException e) {
			return map;
		}

		// 给cs端发刷新消息
		String flag2 = map.get("O_FLAG").toString();
		if (flag2.equals("0")) {
			long timestamp = System.currentTimeMillis();
			String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM213",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
					Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
					Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
					Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
			);

			// BODY 表的 Rows 数据
			List<List<Object>> bodyRows = List.of(
					List.of("I", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 2, 3)
			);

			logger.info("锁定标识为"+3+"需要锁线"+","+"LockLine is"+3);


			// 创建一个 ObjectMapper 实例
			ObjectMapper mapper = new ObjectMapper();

			// 创建一个 Map 并添加数据
			HashMap<String, List<String>> jsonMap = new HashMap<>();
			jsonMap.put("Tracks", List.of(tblXdLjzyjl.getLineCode()));

			// 将 Map 转换为 JSON 字符串
			String jsonString = mapper.writeValueAsString(jsonMap);
			// 发送请求并获取响应

//			String jsonResponse = "[{\"OPERATE_FLAG\":\"I\",\"SEQ\":1,\"WAGONNO\":\"5073\",\"DEVICE_NO\":\"5073\",\"WAGON_TYPE_CODE\":\"\",\"WAGON_TYPE_NAME\":\"5073\",\"WAGON_GROUP_CODE\":\"\",\"WAGON_GROUP_NAME\":\"\",\"STATION_CODE\":\"01\",\"STATION\":\"灵山站\",\"AREA_CODE\":\"0101\",\"AREA\":\"灵山站内区\",\"YARDNO_CODE\":\"010141\",\"SEND_STATION\":\"\",\"ARRIVE_STATION_CODE\":\"\",\"ARRIVE_STATION\":\"\",\"DEST_CODE\":\"\",\"DEST\":\"\",\"GOODS_CODE\":\"\",\"GOODS\":\"\",\"SEND_UNIT_CODE\":\"\",\"SEND_UNIT\":\"\",\"RECEIVE_UNIT_CODE\":\"\",\"RECEIVE_UNIT\":\"\",\"IS_NOPEAK\":\"\",\"IS_PARTIAL\":\"\",\"IS_USE\":\"\",\"USE_STATUS\":\"\",\"NO_USE_STATUS\":\"\"}]";


			List<String> reclist = new ArrayList<>();
			List<String> waglist = new ArrayList<>();
			String  LJZYBH = tblXdLjzyjl.getRecId();
			Integer  WagonNum = tblXdLjzyjl.getWagonNum();
			// 构建 Tables 数据
			List<Map<String, Object>> tables = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
//				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);
			String json = createJson(sysInfo, tables);
			logger.info("@@@@@@@@@@@@@@@"+json);


			String s2 = sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json);
			logger.info("@@@@@@@@@@@@@@@"+s2);


			/*第二次发电文*/
			long timestamp1 = System.currentTimeMillis();
			// 将时间戳转换为 Date 对象
			Date date = new Date(timestamp1);

			// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String formattedDate = sdf.format(date);
			String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo1 = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM233",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis1
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns1 = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
					Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
					Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
					Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
					Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
					Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
					Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
			);

			// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
			List<List<Object>> bodyRows1 = List.of(
					List.of("I",
							2,
							formattedDate,
							tblXdLjzyjl.getLineCode(),
							tblXdLjzyjl.getStationUsercode() ,
							tblXdLjzyjl.getStationUsername(),
							0,
							tblXdLjzyjl.getStationUsername(),
							tblXdLjzyjl.getStationTime())
			);

			// DETAIL 表的 Columns 数据
			List<Map<String, String>> detailColumns = List.of(
					Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
					Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
			);

			// DETAIL 表的 Rows 数据
			List<List<Object>> detailRows = new ArrayList<>();

			// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
			List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());
			// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
			if(wagonList.isEmpty()){
				List<Object> newRow = new ArrayList<>();
				newRow.add("");
				newRow.add("");
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}else{
				for (int i = 0; i < wagonList.size(); i++) {
					// 创建新的行
					List<Object> newRow = new ArrayList<>();

					newRow.add(wagonList.get(i).get("recId"));
					newRow.add(wagonList.get(i).get("wagnNo"));
					// 添加行到 detailRows 中
					detailRows.add(newRow);
				}
			}


			// 构建 Tables 数据
			List<Map<String, Object>> tables1 = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
					Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);



			String json1 = createJson(sysInfo1, tables1);
			logger.info("@@@@@@@@@@@@@@@"+json1);

			String s1 = sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(), json1);
			logger.info("@@@@@@@@@@@@@@@"+s1);

			/*第三次发电文*/

		}


		return map;
	}
	
	/**
	 * 检车结束
	 * @throws SQLException 
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:edit")
	@RequestMapping(value = "updateJCROver")
	@ResponseBody
	public HashMap<String, Object> updateJCROver(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
		HashMap<String, Object> map = new HashMap<>();

//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		String JcrName = tblXdLjzyjlService.selectJnrName(tblXdLjzyjl.getJcrCode());
		String I_IP_ADDR = request.getRemoteHost(); // 取IP
		String I_USERCODE = UserUtils.getUser().getUserCode(); // 取用户id
		String I_USERNAME = UserUtils.getUser().getUserName(); //用户名
		String  LJZYBH = tblXdLjzyjl.getRecId();
		map.put("I_LJZYBH", tblXdLjzyjl.getRecId()); 	// 列检记录编号 传入的REC_ID
		map.put("I_PASSWORD", tblXdLjzyjl.getPassword());	// 口令
		map.put("I_USERCODE", userId); // 登录人用户编号
		map.put("I_USERNAME", userName); // 登录用户名称
		map.put("I_IP", I_IP_ADDR); // 本机IP地址
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1
		try {
			tblXdDjzyjlService.updateJCROver(map);
		} catch (SQLException e) {
			return map;
		}

		// 给cs端发刷新消息
		String flag2 = map.get("O_FLAG").toString();
		if (flag2.equals("0")) {
			long timestamp = System.currentTimeMillis();
			String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
			// SysInfo 数据
			Map<String, Object> sysInfo = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM213",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
					Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
					Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
					Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
			);

			// BODY 表的 Rows 数据
			List<List<Object>> bodyRows = List.of(
					List.of("E", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 1, 0)
			);
			// 构建 Tables 数据
			List<Map<String, Object>> tables = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
			);

			logger.info("锁定标识为"+0+"需要解除锁线"+","+"LockLine is"+0);


			String json = createJson(sysInfo, tables);
			logger.info("@@@@@@@@@@@@@@@"+json);

//			sendJsonWithHttpClient("172.16.16.36",8085,"/lj",json);
			sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json);

			/*第二次发电文*/
			long timestamp1 = System.currentTimeMillis();
			String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
			Date date = new Date(timestamp1);

			// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String formattedDate = sdf.format(date);
			// SysInfo 数据
			Map<String, Object> sysInfo1 = Map.of(
					"Flag", 0,
					"Msg", "",
					"SvcName", "NEM233",
					"Sender", "NE",
					"UUID", timestampWithLast4Millis1
			);

			// BODY 表的 Columns 数据
			List<Map<String, String>> bodyColumns1 = List.of(
					Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
					Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
					Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
					Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
					Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
					Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
					Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
					Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
					Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
			);

			// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
			List<List<Object>> bodyRows1 = List.of(
					List.of("E",
							2,
							formattedDate,
							tblXdLjzyjl.getLineCode(),
							tblXdLjzyjl.getStationUsercode() ,
							tblXdLjzyjl.getStationUsername(),
							0,
							tblXdLjzyjl.getStationUsername(),
							tblXdLjzyjl.getStationTime() )
			);

			// DETAIL 表的 Columns 数据
			List<Map<String, String>> detailColumns = List.of(
					Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
					Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
			);

			// DETAIL 表的 Rows 数据
			List<List<Object>> detailRows = new ArrayList<>();

			List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());

			// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
			if(wagonList.isEmpty()){
				List<Object> newRow = new ArrayList<>();
				newRow.add("");
				newRow.add("");
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}else{
				for (int i = 0; i < wagonList.size(); i++) {
					// 创建新的行
					List<Object> newRow = new ArrayList<>();

					newRow.add(wagonList.get(i).get("recId"));
					newRow.add(wagonList.get(i).get("wagnNo"));
					// 添加行到 detailRows 中
					detailRows.add(newRow);
				}
			}

			// 构建 Tables 数据
			List<Map<String, Object>> tables1 = List.of(
					Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
					Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
			);



			String json1 = createJson(sysInfo1, tables1);
			logger.info("@@@@@@@@@@@@@@@"+json1);

//			sendJsonWithHttpClient("172.16.16.36",8085,"/lj",json1);
			sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json1);

			/*第三次发电文*/


		}

		return map;
	}
	
	/**
	 * 取消
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:edit")
	@RequestMapping(value = "cancel")
	@ResponseBody
	public String cancel(TblXdLjzyjl tblXdLjzyjl, HttpServletRequest request) throws Exception {
		HashMap<String, Object> map = new HashMap<>();
//		HttpSession session = request.getSession();
//		String sessionId = session.getId();
//		String userId = tblXdLjzyjlService.selectUserData(sessionId);
		String userId = JsonGenerator.extractAndDecodeAccessToken(request);
		String userName = tblZdWorkerdzDao.selectName1(userId);
		String I_IP_ADDR = request.getRemoteHost(); // 取IP
		String I_USERCODE = UserUtils.getUser().getUserCode(); // 取用户id
		String I_USERNAME = UserUtils.getUser().getUserName(); //用户名

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		map.put("I_LJZYBH", tblXdLjzyjl.getRecId()); 	// 列检记录编号 传入的REC_ID
		map.put("I_TIME", format.format(new Date()));	// 口令
		map.put("I_USERCODE", userId); // 登录人用户编号
		map.put("I_USERNAME", userName); // 登录用户名称
		map.put("I_IP", I_IP_ADDR); // 本机IP地址
		map.put("I_TYPECODE", tblXdLjzyjl.getTypeCode());// 动检2列检1
		try {
			tblXdDjzyjlService.cancel(map);
		} catch (SQLException e) {
			return renderResult(Global.FALSE, text("取消失败！"));
		}

		long timestamp = System.currentTimeMillis();
		String timestampWithLast4Millis = timestamp + String.format("%04d", timestamp % 10000);
		// SysInfo 数据
		Map<String, Object> sysInfo = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM213",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis
		);

		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道代码"),
				Map.of("Name", "STATION_TRACK_CNAME", "DataType", "S", "Caption", "股道名称"),
				Map.of("Name", "USING_STATE", "DataType", "S", "Caption", "运用状态"),
				Map.of("Name", "LOCK_FLAG", "DataType", "S", "Caption", "锁定标记")
		);

		// BODY 表的 Rows 数据
		List<List<Object>> bodyRows = List.of(
				List.of("C", tblXdLjzyjl.getLineCode(), tblXdLjzyjl.getLine(), 1, 0)
		);

		// 构建 Tables 数据
		List<Map<String, Object>> tables = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns, "Rows", bodyRows)
//				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
		);

		logger.info("锁定标识为"+0+"需要解除锁线"+","+"LockLine is"+0);
		String json = createJson(sysInfo, tables);

		System.out.println(json);

		ObjectMapper Obj = new ObjectMapper();

		logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+json);
//		sendJsonWithHttpClient("172.16.16.36",8085,"/lj",json);
		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json);


		/*第二次发电文*/
		long timestamp1 = System.currentTimeMillis();
		String timestampWithLast4Millis1 = timestamp1 + String.format("%04d", timestamp % 10000);
		Date date = new Date(timestamp1);

		// 使用 SimpleDateFormat 格式化时间戳为 yyyyMMddHHmmss 格式的字符串
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedDate = sdf.format(date);
		// SysInfo 数据
		Map<String, Object> sysInfo1 = Map.of(
				"Flag", 0,
				"Msg", "",
				"SvcName", "NEM233",
				"Sender", "NE",
				"UUID", timestampWithLast4Millis1
		);

		// BODY 表的 Columns 数据
		List<Map<String, String>> bodyColumns1 = List.of(
				Map.of("Name", "OPERATE_FLAG", "DataType", "S", "Caption", "操作标志"),
				Map.of("Name", "STATUS", "DataType", "S", "Caption", "标识"),
				Map.of("Name", "OPERATION_TIME", "DataType", "S", "Caption", "操作时间"),
				Map.of("Name", "STATION_TRACK", "DataType", "S", "Caption", "股道号"),
				Map.of("Name", "OPERATOR_NO", "DataType", "S", "Caption", "操作人编号"),
				Map.of("Name", "OPERATOR", "DataType", "S", "Caption", "操作人名称"),
				Map.of("Name", "WAGON_NUM", "DataType", "S", "Caption", "车数"),
				Map.of("Name", "STATION_USER", "DataType", "S", "Caption", "车站调度"),
				Map.of("Name", "STATION_TIME", "DataType", "S", "Caption", "车站通知时间")
		);

		// BODY 表的 Rows 数据 操作标记I是开始 E是结束  标识 1是列检 2是动检
		List<List<Object>> bodyRows1 = List.of(
				List.of("C", 2, formattedDate,
						tblXdLjzyjl.getLineCode(),
						userId,
						userName,
						0,
						tblXdLjzyjl.getStationUsername(),
						tblXdLjzyjl.getStationTime() )
		);

		// DETAIL 表的 Columns 数据
		List<Map<String, String>> detailColumns = List.of(
				Map.of("Name", "REC_ID", "DataType", "S", "Caption", "记录编号"),
				Map.of("Name", "WAGONNO", "DataType", "S", "Caption", "车号")
		);

		// DETAIL 表的 Rows 数据
		List<List<Object>> detailRows = new ArrayList<>();

		List<Map<String,String>> wagonList =  tblXdLjzyjlService.getWagonList(tblXdLjzyjl.getRecId());

		// 循环遍历 tblXdLjzyjlList，将数据动态添加到 detailRows 中
		if(wagonList.size()==0){
			List<Object> newRow = new ArrayList<>();
			newRow.add("");
			newRow.add("");
			// 添加行到 detailRows 中
			detailRows.add(newRow);
		}else{
			for (int i = 0; i < wagonList.size(); i++) {
				// 创建新的行
				List<Object> newRow = new ArrayList<>();

				newRow.add(wagonList.get(i).get("recId"));
				newRow.add(wagonList.get(i).get("wagnNo"));
				// 添加行到 detailRows 中
				detailRows.add(newRow);
			}
		}

		// 构建 Tables 数据
		List<Map<String, Object>> tables1 = List.of(
				Map.of("Name", "BODY", "Columns", bodyColumns1, "Rows", bodyRows1),
				Map.of("Name", "DETAIL", "Columns", detailColumns, "Rows", detailRows)
		);



		String json1 = createJson(sysInfo1, tables1);
		logger.info("@@@@@@@@@@@@@@@"+json1);

//		sendJsonWithHttpClient("172.16.16.36",8085,"/lj",json1);
		sendJsonWithHttpClient(serverTrexConfig.getAddress(), serverTrexConfig.getPort(), serverTrexConfig.getMethod(),json1);

		return renderResult(Global.TRUE, text("取消成功！"));
	}
	
	/**
	 * 删除数据
	 */
	//@RequiresPermissions("tbl:tblXdDjzyjl:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TblXdLjzyjl tblXdLjzyjl) {
		tblXdDjzyjlService.delete(tblXdLjzyjl);
		return renderResult(Global.TRUE, text("删除列检作业记录成功！"));
	}
	
}